package rush.rushcampus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import rush.rushcampus.common.BaseContext;
import rush.rushcampus.dto.FoundPublicationDto;
import rush.rushcampus.dto.FoundPageDto;
import rush.rushcampus.entity.*;
import rush.rushcampus.mapper.ArticleMapper;
import rush.rushcampus.mapper.CommentMapper;
import rush.rushcampus.mapper.FoundMapper;
import rush.rushcampus.mapper.FoundTagMapper;
import rush.rushcampus.service.IFoundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import rush.rushcampus.vo.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rush
 * @since 2024-06-14
 */
@Service
public class FoundServiceImpl extends ServiceImpl<FoundMapper, Found> implements IFoundService {
    @Autowired
    private FoundTagMapper foundTagMapper;
    @Autowired
    private FoundMapper foundMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private UserServiceImpl userService;

    //发布失物招领信息
    @Override
    public void addFound(FoundPublicationDto foundPublicationDto) {
        Found found = new Found();
        BeanUtils.copyProperties(foundPublicationDto, found);
        found.setAuthorId(BaseContext.getCurrenId());
        found.setStatus(0);
        found.setViewCount(0L);
        found.setLikeCount(0L);
        found.setCreateTime(LocalDateTime.now());
        found.setTagList("[]");
        found.setId(BaseContext.getCurrenId());

        this.save(found);
    }

    @Override
    public List<FoundAllVo> listFound(FoundPageDto foundPageDto) {
        Integer currentPage = foundPageDto.getPage();
        Integer pageSize = foundPageDto.getSize();

        List<FoundAllVo> foundAllVoList = new ArrayList<>();
        Page<Found> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Found> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", foundPageDto.getStatus());

        // 检查 FoundTagId 是否非 0，如果非 0，则在查询条件中加入该条件
//        if (foundPageDto.getFoundTagId() != 0) {
//            queryWrapper.like("tag_list", foundPageDto.getFoundTagId().toString());

//        }
        queryWrapper.apply(foundPageDto.getFoundTagId()!=null , "FIND_IN_SET({0} , tag_list)", foundPageDto.getFoundTagId());

        if (foundPageDto.getStar()!= null){
            List<Long> starList = Arrays.stream(foundPageDto.getStar().split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            queryWrapper.in("id" , starList);
        }
        // 执行分页查询
        List<Found> foundList = foundMapper.selectPage(page, queryWrapper).getRecords();

        // 遍历查询到的记录，处理标签信息
        for (Found found1 : foundList) {
            String foundTagId = found1.getTagList();
            List<FoundTag> tagList = new ArrayList<>();
            Pattern pattern = Pattern.compile("\\d+");
            Matcher matcher = pattern.matcher(foundTagId);

            // 获取标签列表
            while (matcher.find()) {
                String tagId = matcher.group();
                FoundTag foundTag = foundTagMapper.selectById(tagId);
                tagList.add(foundTag);
            }

            // 创建 VO 对象并复制属性
            FoundAllVo foundAllVo = new FoundAllVo();
            BeanUtils.copyProperties(found1, foundAllVo);
            foundAllVo.setTagsList(tagList);
            foundAllVoList.add(foundAllVo);
        }

        return foundAllVoList;
    }
    @Transactional
    @Override
    public void removeFound(Long id , Integer commentType) {
        //1.删除评论
        commentService.deleteCommentAndChildren(id ,commentType);
        //2.删除found
        this.removeById(id);
    }

    @Override
    public FoundInfoVo getFoundById(Long id) {
        QueryWrapper<Found> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.eq("id", id);
        Found found = getOne(queryWrapper);
        articleMapper.incrementFoundViewById(id);
        User user = userService.getById(found.getAuthorId());
        UserPartInfoVo userPartInfoVo = new UserPartInfoVo();
        userPartInfoVo.setCreateUserName(user.getNickname());
        userPartInfoVo.setCreateUserAvatar(user.getAvatar());
        userPartInfoVo.setCreateUserSex(user.getGender());
        FoundInfoVo foundInfoVo = new FoundInfoVo();
        foundInfoVo.setUserPartInfoVo(userPartInfoVo);
        foundInfoVo.setCreateTime(found.getCreateTime());
        foundInfoVo.setView(found.getViewCount());
        foundInfoVo.setLoveNumber(found.getLikeCount());
        foundInfoVo.setStarNumber(found.getStarCount());
        foundInfoVo.setCommentNumber(commentService.countComment(id, 1));
        foundInfoVo.setContent(found.getContent());
        foundInfoVo.setImgList(found.getImgList());
        //查询评论，赋值
//        List<ArticleCommentVo> articleCommentVoList = commentService.listComment(id, 0, 1, 10);
        List<ArticleCommentVo> articleCommentVoList = commentService.listArticleComment(id , 1);
        foundInfoVo.setArticleCommentVoList(articleCommentVoList);
        return foundInfoVo;
    }


    public void starFound(Long id, Integer isStar) {
        Found found = this.getById(id);
        if (isStar == 1){
            found.setStarCount(found.getStarCount() + 1);
        }else {
            found.setStarCount(found.getStarCount() - 1);
        }
        this.updateById(found);
        }

    }

